package cn.springcloud.fix.stomp.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Slf4j
@Getter
@Setter
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "thread-pool" )
public class TaskExecutorConfig implements AsyncConfigurer {

    private Integer corePoolSize = 10;
    private Integer maxPoolSize = 20;
    private Integer queueCapacity = 100;
    private Integer waitExitSeconds = 60;

    @Bean("threadPoolTaskExecutor" )
    public TaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);// 线程池大小
        taskExecutor.setMaxPoolSize(maxPoolSize);// 线程池最大线程数
        taskExecutor.setQueueCapacity(queueCapacity);// 最大等待任务数
        taskExecutor.setThreadNamePrefix("spa-exec-" );
        // 关闭线程池时等待线程处理完成
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置等待线程关闭的时间
        taskExecutor.setAwaitTerminationSeconds(waitExitSeconds);
        taskExecutor.initialize();
        log.info("init taskExecutor, corePoolSize:{}, maxPoolSize:{}, queueCapacity:{}" , corePoolSize, maxPoolSize, queueCapacity);
        return taskExecutor;
    }
}
